//
//  LGBloodPressureController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/3.
//  血压

#import "LGBloodPressureController.h"
//心电图
#import "LGECGDetailViewController.h"
#import "LGECGDetailViewController2.h"
#import "LGECGDetailEmptyController.h"
//统计图
#import "LGBloodPressureChart.h"
#import "LGHeartRateChartView.h"
#import "LGMonitoringHistoryView.h"
#import "LGBloodPressureCell.h"
//区头
#import "LGBloodPressureHeader.h"
#import "LGChartDetailAlertView.h"

#import "LGPickerView.h"
@interface LGBloodPressureController ()<LGBloodPressureChartDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,LGBloodPressureCellDelegate>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIView *footerView;
/**   */
@property (nonatomic , strong)LGBloodPressureChart *chartView;
/**   */
@property (nonatomic , strong)LGHeartRateChartView *heartView;
/**   */
@property (nonatomic , strong)LGMonitoringHistoryView *historyView;
/**   */
@property (nonatomic , strong)LGChartDetailAlertView *alertView;
/**   */
@property (nonatomic , copy)NSString *monthString;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter1;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter2;
/**   */
@property (nonatomic , assign)BOOL firstLoad;
@end

@implementation LGBloodPressureController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.firstLoad = YES;
    self.monthString = [self.formatter2 stringFromDate:[NSDate date]];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.alertView];
    self.emptyView.userInteractionEnabled = NO;
    self.emptyView.backgroundColor = [UIColor clearColor];
}

//模块被选中
-(void)viewWillAppearAction{
    if(self.firstLoad == YES){
        [self requestData];
        [self requestHistoryData];
        self.firstLoad = NO;
    }
    if(self.chartView.dataDic.allKeys.count == 0){
        [self requestData];
    }
    if (self.dataArray.count == 0) {
        [self requestHistoryData];
    }
}


//统计图数据
-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.Physicalsign/bpEcharts" parameters:@{@"timeframe":@"30",@"patient_id":self.patientid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        if(code == 200){
            self.chartView.dataDic = returnData;
            self.heartView.dataDic = returnData;
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
    }];
    if (self.dataArray.count == 0) {
        [self requestHistoryData];
    }
}

//请求历史记录
-(void)requestHistoryData{
    [RequestUtil withPOST:@"/doctor/patient.Physicalsign/bpList" parameters:@{@"timeframe":self.monthString,@"patient_id":self.patientid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(code == 200){
            self.dataArray = returnData;
            [self.tableView reloadData];
        }
        if(self.dataArray.count == 0){
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(300));
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(60)];
        }else{
            self.footerView.frame = CGRectMake(0, 0, Screen_W, 0.001);
        }
        self.tableView.tableFooterView = self.footerView;
    } error:^(NSError *error) {
        self.isfirst = NO;
        if(self.dataArray.count == 0){
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(300));
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(60)];
        }else{
            self.footerView.frame = CGRectMake(0, 0, Screen_W, 0.001);
        }
        self.tableView.tableFooterView = self.footerView;
    }];
}

//选择月份
-(void)showMonthPickerView{
    NSMutableArray *yearArray = [NSMutableArray array];
    NSArray *monthArray = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
    for (NSInteger i=2020; i<2100; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%ld",i]];
    }
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.pickArry = @[yearArray,monthArray];
    pickerView.titleLabel.text = @"请选择月份";
    pickerView.units = @[@"年",@"月"];
    pickerView.selectStr = [self.monthString stringByReplacingOccurrencesOfString:@"-" withString:@"|"];
    [self.view.window addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
        weakSelf.historyView.monthLabel.text = [NSString stringWithFormat:@"%@年%@月",resultArray[0],resultArray[1]];
        weakSelf.monthString = [NSString stringWithFormat:@"%@-%@",resultArray[0],resultArray[1]];
        [weakSelf requestHistoryData];
    };
}

//某点的详细数据
-(void)showAlertView:(NSArray *)dataArray date:(NSString *)dateString point:(CGPoint)point{
    CGFloat marginX = (point.x>Screen_W/2.0)?(point.x-viewPix(140)-5):(point.x+5);
    self.alertView.frame = CGRectMake(marginX, point.y+3, viewPix(140), viewPix(35)+viewPix(24)*dataArray.count);
    self.alertView.dateString = dateString;
    self.alertView.dataArray = dataArray;
    self.alertView.hidden = NO;
    if(point.x>Screen_W/2.0){
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.alertView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(15, 15)];
        self.alertView.cornerLayer.path = path.CGPath;
    }else{
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.alertView.bounds byRoundingCorners: UIRectCornerTopRight|UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(15, 15)];
        self.alertView.cornerLayer.path = path.CGPath;
    }
}

//查看心电图
-(void)checkECGDetail:(NSDictionary *)dataDic{
    NSString *source = LGNSString(dataDic[@"source"]);
    if ([source isEqualToString:@"BP"] || [source isEqualToString:@"add"]) {
        //心电图1
        LGECGDetailViewController *controller = [[LGECGDetailViewController alloc]init];
        controller.ecgId = LGNSString(dataDic[@"ecg_id"]);
        controller.patientid = self.patientid;
        [self.navigationController pushViewController:controller animated:YES];
    }else if ([source isEqualToString:@"KPQ"]||[source isEqualToString:@"KPQ6"]){
        //卡帕奇 、 卡帕奇6导
        NSString *warm = LGNSString(dataDic[@"ecg_warm"]);
        if ([warm isEqualToString:@"2"]) {
            //干扰数据
            LGECGDetailEmptyController *controller = [[LGECGDetailEmptyController alloc]init];
            controller.source = source;
            [self.navigationController pushViewController:controller animated:YES];
            
        }else{
            LGECGDetailViewController2 *controller = [[LGECGDetailViewController2 alloc]init];
            controller.ecgId = LGNSString(dataDic[@"ecg_id"]);
            controller.patientid = self.patientid;
            controller.source = source;
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *tempArray = self.dataArray[section][@"children"];
    return tempArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGBloodPressureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *tempArray = self.dataArray[indexPath.section][@"children"];
    cell.dataDic = tempArray[indexPath.row];
    cell.delegate = self;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return viewPix(75);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LGBloodPressureHeader *headView = [[LGBloodPressureHeader alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(75))];
    headView.monthLabel.text = self.dataArray[section][@"record_date"];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return viewPix(15);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(15))];
    footView.shadowView.backgroundColor = [UIColor colorWithString:@"#F6FAFE"];
    footView.backgroundColor = [UIColor clearColor];
    footView.bottomMargin = viewPix(10);
    return footView;
}

-(void)chartViewTouchesBegan{
    self.alertView.hidden = YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self chartViewTouchesBegan];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self chartViewTouchesBegan];
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 0, Screen_W, self.view.bounds.size.height);
}

#pragma mark
#pragma mark ====> 创建控件

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, self.view.bounds.size.height) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGBloodPressureCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = viewPix(35);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(720))];
        [headerView addSubview:self.chartView];
        [headerView addSubview:self.heartView];
        [headerView addSubview:self.historyView];
        _tableView.tableHeaderView = headerView;
        _tableView.tableFooterView = self.footerView;
    }
    return _tableView;
}

-(LGBloodPressureChart *)chartView{
    if(!_chartView){
        _chartView = [[LGBloodPressureChart alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(360))];
        _chartView.delegate = self;
    }
    return _chartView;
}

-(LGHeartRateChartView *)heartView{
    if(!_heartView){
        _heartView = [[LGHeartRateChartView alloc]initWithFrame:CGRectMake(0, kMaxY(self.chartView.frame)+viewPix(16), Screen_W, viewPix(270))];
        _heartView.delegate = self;
    }
    return _heartView;
}

-(LGMonitoringHistoryView *)historyView{
    if(!_historyView){
        _historyView = [[LGMonitoringHistoryView alloc] initWithFrame:CGRectMake(0, kMaxY(self.heartView.frame)+viewPix(15), Screen_W, viewPix(70))];
        _historyView.monthLabel.text = [self.formatter1 stringFromDate:[NSDate date]];
        [_historyView.monthBtn addTarget:self action:@selector(showMonthPickerView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _historyView;
}

-(LGChartDetailAlertView *)alertView{
    if(!_alertView){
        _alertView = [[LGChartDetailAlertView alloc] initWithFrame:CGRectMake(0, 0, viewPix(140), viewPix(50))];
        _alertView.hidden = YES;
    }
    return _alertView;
}

-(UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(300))];
        [self emptyViewWithSuperView:_footerView frame:_footerView.bounds];
    }
    return _footerView;
}

-(NSDateFormatter *)formatter1{
    if(!_formatter1){
        _formatter1 = [[NSDateFormatter alloc] init];
        _formatter1.dateFormat = @"YYYY年MM月";
    }
    return _formatter1;
}

-(NSDateFormatter *)formatter2{
    if(!_formatter2){
        _formatter2 = [[NSDateFormatter alloc] init];
        _formatter2.dateFormat = @"YYYY-MM";
    }
    return _formatter2;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
